const {
	ObjectID,
	MongoClient,
} = require('mongodb')

module.exports = class Mongo {
	constructor(url, dbName) {
		this.__url = url
		this.__dbName = dbName
	}

	init() {
		return init.call(this)
	}

	__checkConnect() {
		return checkConnect.call(this)
	}

	setDB(dbName) {
		if (dbName)
			this.__dbName = dbName
	}

	setIndex(colName, indexArr) {
		return setIndex.call(this, colName, indexArr)
	}

	getDB() {
		if (this.__client && this.__dbName)
			return this.__client.db(this.__dbName)
		return null
	}

	getCollection(colName) {
		return getCollection.call(this, colName)
	}

	static ObjectID(...args) {
		return ObjectID(...args)
	}
}

async function init() {
	this.__client = await MongoClient.connect(this.__url)
	return this.__client
}

async function checkConnect() {
	if (!this.__client || (typeof this.__client.isConnected == 'function' && !this.__client.isConnected()))
		this.__client = await MongoClient.connect(this.__url)
}

async function getCollection(colName) {
	if (!colName)
		throw new Error(`---colName is ${colName}---`)
	await this.__checkConnect()
	let db = this.__client.db(this.__dbName)
	let colArr = await db.listCollections({
		name: colName,
	}).toArray()
	let collection = db.collection(colName)
	// 判断该集合(collection)是否存在
	if (colArr.length < 1)
		collection = await db.createCollection(colName)
	return collection
}

async function setIndex(colName, indexArr) {
	if (!colName)
		return
	await this.__checkConnect()
	let db = this.__client.db(this.__dbName)
	let colArr = await db.listCollections({
		name: colName,
	}).toArray()
	let collection = db.collection(colName)

	// 判断该集合(collection)是否存在
	if (colArr.length < 1)
		collection = await db.createCollection(colName)

	if (!Array.isArray(indexArr) || indexArr.length < 1)
		return

	/**
	 * 创建索引
	 * @param  {string} colName      	集合名称
	 * @param  {Array} indexArr 		集合索引
	 *         indexArr数组中的为string/object类型
	 *         object = {
	 *         		name:'', 索引名称
	 *         		opts:{}  索引可选项,参照mongodb createIndex API
	 *         }
	 * 
	 * @return {Promise}         		[description]
	 */
	for (let i = 0; i < indexArr.length; i++) {
		let index = indexArr[i]
		let uuidIndex = await collection.indexExists(index.name || index)
		if (!uuidIndex) {
			let name = index.name || index
			let opts = index.opts || {}
			opts.name = opts.name || name
			collection.createIndex(name, opts)
		}
	}
	return
}